import { isRealTime } from '@/components/common/auto-refresh/auto-refresh-util.js';
import { CAN_AUTO_REFRESH_TYPE } from '@/utils/constant.js';
import { visualAction } from '@/utils/util';
import dm5 from 'lib/dm5.js';
export default {
  data() {
    return {
      apiCacheKey: '',
    };
  },
  computed: {

    // push模式实时数据
    isRealTime() {
      return isRealTime(this.config.config.data);
    },
  },
  methods: {
    autoRefresh() {
      if (this.timers.autoRefresh) { // 只在第一次显示loading效果
        this.isLoading = false;
      }
      let { autoRefresh = {}, dataSourceType } = this.config.config.data || {};
      if (this.curComp) {
        ({ autoRefresh, dataSourceType } = this.config.config.data[this.curComp]);
      }
      clearTimeout(this.timers.autoRefresh);
      const canAutoRefreshType = CAN_AUTO_REFRESH_TYPE.includes(dataSourceType);
      if (canAutoRefreshType && autoRefresh.switchEnable && autoRefresh.actType === 'pull') {
        this.timers.autoRefresh = setTimeout(() => {
          this.debounceGetData();
        }, autoRefresh.interval * 1000);
      }
    },

    autoRefreshIsSameRes(apiResult, data) {
      if (visualAction() === 'saveAllData') {
        this.apiCacheKey = '';
        return false;
      }
      let { switchEnable = false } = this.config.config.data.autoRefresh || {};
      if (data) {
        switchEnable = data.autoRefresh.switchEnable;
      }
      const { dataSourceType } = this.config.config.data || {};

      // redis实时数据和xvueApi 没有开启实时数据的开关
      const hasNoSwitchEnable = ['xMinerRedisRealTime', 'xVueApi'].includes(dataSourceType);

      if (!switchEnable && !hasNoSwitchEnable) {
        this.apiCacheKey = '';
        return false;
      }

      const dm5Key = dm5(apiResult);
      const isSameResult = this.apiCacheKey && dm5Key === this.apiCacheKey;
      this.apiCacheKey = dm5Key;
      return isSameResult;
    },

    getResult(realTimeData) {
      let result;
      this.isNoData = false;
      this.isLoading = true;
      const { datalist } = realTimeData || {};
      if (!datalist || !datalist.length || !datalist[0].data || !datalist[0].data.length) {
        this.isNoData = true;
      } else {
        result = datalist[0].data;
      }
      return result;
    },
  },
};
